import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * Created by yangxiaosi01 on 2019/3/7.
 */
public class AliyunOSSClientUtils {
    //log日志
    private static Log logger = LogFactory.getLog(AliyunOSSClientUtils.class);
    //阿里云API的内或外网域名
    private static String ENDPOINT;
    //阿里云API的密钥Access Key ID
    private static String ACCESS_KEY_ID;
    //阿里云API的密钥Access Key Secret
    private static String ACCESS_KEY_SECRET;
    //阿里云API的bucket名称
    private static String BACKET_NAME;
    //阿里云API的文件夹名称
    private static String FOLDER;
    //初始化属性
    static{
        ENDPOINT = OSSClientConstants.ENDPOINT;
        ACCESS_KEY_ID = OSSClientConstants.ACCESS_KEY_ID;
        ACCESS_KEY_SECRET = OSSClientConstants.ACCESS_KEY_SECRET;
        BACKET_NAME = OSSClientConstants.DEFAULT_BACKET_NAME;
        FOLDER = OSSClientConstants.DEFAULT_FOLDER;
    }
    /**
     * 获取阿里云OSS客户端对象
     * @return ossClient
     */
    public static OSSClient getOSSClient(){
        return new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }

    /**
     * 获取阿里云OSS客户端对象
     * @return ossClient
     */
    public static void shutdownOSSClient(OSSClient ossClient){
        ossClient.shutdown();
    }

    /**
     * 把文件保存到阿里云OSS，返回ossurl
     * @param ossClient oss链接
     * @param fileupload InputStream类型 任何格式图片均可,最终存储为jpg
     * @return url
     */
    public static String uploadAndReturnUrl(OSSClient ossClient,InputStream fileupload) throws OSSException, ClientException, IOException {
        // 文件名格式 32uuid
        String filename = UUID.randomUUID().toString().replace("-", "")+".jpg";
        // 上传文件
        ossClient.putObject(BACKET_NAME, filename,fileupload);
        // 设置URL过期时间为100年，默认这里是int型，转换为long型即可
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(BACKET_NAME, filename, expiration);

        return url.toString();
    }

    /**
     * 根据url删除OSS服务器上的文件
     * @param ossClient oss链接
     * @param ossurl 文件url
     */
    public static void deleteFileByOssUrl( OSSClient ossClient,String ossurl){
        int begin=ossurl.indexOf(".com/");
        int last=ossurl.indexOf(".jpg?");
        String filename = ossurl.substring(begin+5,last)+".jpg";
        ossClient.deleteObject(BACKET_NAME, filename);
        logger.info("删除" + BACKET_NAME + "下的文件"  + filename + "成功");
    }
    /**
     * 根据key删除OSS服务器上的文件
     * @param ossClient oss链接
     * @param filename 文件路径+名称
     */
    public static void deleteFilebyFileName(OSSClient ossClient, String filename){
        ossClient.deleteObject(BACKET_NAME, filename);
        logger.info("删除" + BACKET_NAME + "下的文件"  + filename + "成功");
    }

    //使用范例
    public static void main(String[] args) {
        //首先获取链接OSSClient，链接信息使用默认的即可
        OSSClient ossClient = getOSSClient();

        /*File file=new File("D:\\image\\101111.jpg");
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            System.out.println(uploadAndReturnUrl(ossClient , is));
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        String url="http://hotel-test-oss-bucket.oss-cn-beijing.aliyuncs.com/433ec3e22e13478d9be241c578b39f06.jpg?Expires=1552212996&OSSAccessKeyId=TMP.AQHUwFzmLWot4TnXfTfDFYGx7yPwhGOudB_A3dW3BoRjDNVj9nXvXnRLKPOUADAtAhUAmRf4Vkr-zPuGdbQnjxBCjGbrCCkCFELuVJRgza7D_PD-EMk2ej4effEw&Signature=4ceb3PnEz3cLdFn%2Bl1Jgrakv4DI%3D";
        //传参url进行删除,一般使用该方式进行文件删除
        deleteFileByOssUrl(ossClient,url);

        //传参文件名进行删除，文件名为32位uuid+".jpg"
        deleteFilebyFileName(ossClient,"86a63725122e4ae8ae426a8565cefff8");

        //最后关闭OSSClient
        shutdownOSSClient(ossClient);
    }
}
